package cn.crystalling.app.attendance;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private static final int FILE_SELECT_CODE = 0;

    ListView listView;
    ListViewAdapter adapter;
    ArrayList<Student> studentList;
    boolean isCheck = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initListView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.checkMenuItem: {
                if (!isCheck) {
                    showAbsence();
                    isCheck = true;
                    item.setIcon(R.drawable.check_done);
                } else {
                    showAll();
                    isCheck = false;
                    item.setIcon(R.drawable.check);
                }
                return true;
            }
            case R.id.importCSVMenuItem: {
                setCSVData();
                return true;
            }
            case R.id.helpMenuItem: {
                Intent intent = new Intent(this,HelpActivity.class);
                startActivity(intent);
                return true;
            }
        }
        return false;
    }

    private void showAbsence() {
        HashMap<Integer, View> viewMap = adapter.getViewMap();
        for (int index = 0; index < viewMap.size(); index++) {
            View view = viewMap.get(index);
            RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
            RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
            if (radioButton != null) {
                if (radioButton.getId() == R.id.trueBtn) {
                    studentList.get(index).setState(1);
                } else if (radioButton.getId() == R.id.falseBtn) {
                    studentList.get(index).setState(2);
                } else if (radioButton.getId() == R.id.otherReasonBtn) {
                    studentList.get(index).setState(3);
                }
            }
        }
        ArrayList<Student> temp = new ArrayList<>();
        for (Student stu : studentList) {
            if (stu.getState() != 1) {
                temp.add(stu);
            }
        }
        adapter = new ListViewAdapter(this, temp);
        listView.setAdapter(adapter);
    }

    private void showAll(){
        HashMap<Integer, View> viewMap = adapter.getViewMap();
        for (int index = 0; index < viewMap.size(); index++) {
            View view = viewMap.get(index);
            String textNum = ((TextView)view.findViewById(R.id.numTxt)).getText().toString();
            int num;
            try {
                num = Integer.parseInt(textNum) - 1;
            }catch (Exception e){
                Toast.makeText(this,textNum + "  序号错误，转换失败!",Toast.LENGTH_SHORT).show();
                continue;
            }
            RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
            RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
            if (radioButton != null) {
                if (radioButton.getId() == R.id.trueBtn) {
                    studentList.get(num).setState(1);
                } else if (radioButton.getId() == R.id.falseBtn) {
                    studentList.get(num).setState(2);
                } else if (radioButton.getId() == R.id.otherReasonBtn) {
                    studentList.get(num).setState(3);
                }
            }
        }
        adapter = new ListViewAdapter(this, studentList);
        listView.setAdapter(adapter);
    }

    private void setCSVData() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择要使用的文件管理器"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
        }

    }

    private void initListView() {
        SharedPreferences shared = getSharedPreferences("Attendance_SP", MODE_PRIVATE);
        String path = shared.getString("csvPath", null);
        if (path == null) {
            Toast.makeText(this, "请导入CSV文件", Toast.LENGTH_SHORT).show();
        } else {
            studentList = DataHelper.readCSV(this, path);
            adapter = new ListViewAdapter(this, studentList);
            listView = (ListView) findViewById(R.id.listView);
            listView.setAdapter(adapter);
        }
    }

    @SuppressWarnings("all")
    public String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
                cursor.close();
            } catch (Exception e) {
                Toast.makeText(this, "获取路径错误！", Toast.LENGTH_SHORT).show();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    @SuppressWarnings("all")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    //得到URL的路径
                    Uri uri = data.getData();
                    //得到路径
                    String path = getPath(this, uri);
                    //把路径存入SharedPreferences,设为默认路径
                    String[] strPath = path.split("/");
                    String newPath = getExternalFilesDir("").getPath() + "/" + strPath[strPath.length - 1];
                    if (DataHelper.copyCSV(this, path, newPath)) {
                        Toast.makeText(this, "导入成功！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "导入失败！", Toast.LENGTH_SHORT).show();
                    }

                    SharedPreferences shared = getSharedPreferences("Attendance_SP", MODE_PRIVATE);
                    SharedPreferences.Editor editor = shared.edit();
                    editor.putString("csvPath", newPath);
                    editor.apply();
                    initListView();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
